package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.util.HttpUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.json.JSONArray;
import kong.unirest.json.JSONObject;

import java.math.BigDecimal;
import java.util.*;

public class CourseRegisterController {
    @FXML
    private TextField name, teacherId, credit, Location, capacity, from, to;
    @FXML
    private TextArea description;
    @FXML
    private ComboBox<String> collegeName, termName,type, assessment, typeComboBox;
    @FXML
    private Label success;
    @FXML
    private GridPane coursegridPane;
    @FXML
    private StackPane stackPane1, stackPane2, stackPane3, stackPane4, stackPane5,
            stackPane6, stackPane7, stackPane8, stackPane9, stackPane10, stackPane11, stackPane12, stackPane13,
            stackPane14, stackPane15, stackPane16, stackPane17, stackPane18, stackPane19, stackPane20, stackPane21,
            stackPane22, stackPane23, stackPane24, stackPane25, stackPane26, stackPane27, stackPane28, stackPane29,
            stackPane30, stackPane31, stackPane32, stackPane33, stackPane34, stackPane35;
    Map<Integer, String> map1 = new HashMap<>();
    Map<Integer, String> map2 = new HashMap<>();
    final private Map<StackPane, String> stackPaneToTimeMap = new HashMap<>();

    int collegeid;
    int termid ;
    private List<String> selectedCells = new ArrayList<>();
    JSONArray jsonArray = new JSONArray();

    public void initialize() {
        //userToken设置
//        Globalvar.userToken ="eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIyMDI0OTk5OSIsImlhdCI6MTcxNjM5MjczNiwiZXhw
//        IjoxNzE2NDAxMzc2fQ.T3polC8AGsGNANqvgt96yaIAGHC-uGl_6M7ZKmsw-43VWfjBkdfHnuGirENw26U6vAoI8E04Sbie4FT7L7XfuA";
        //获取学院列表
        HttpResponse<JsonNode> response1 = HttpUtil.get(Globalvar.baseUrl + "/api/colleges")
                .header("Accept", "application/json")
                .asJson();
        JsonNode responseBody1 = response1.getBody();
        JSONArray jsonArray1 = responseBody1.getArray();
        ObservableList<String> items01= FXCollections.observableArrayList();
        for (int i = 0; i < jsonArray1.length(); i++) {
            JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
            String collegename= jsonObject1.getString("collegeName");
            Integer collegeId= jsonObject1.getInt("collegeId");//存储collegeId
            collegeName.getItems().add(collegename);
            map1.put(collegeId, collegename);
        }

        //获取学期列表
        HttpResponse<JsonNode> response2 = HttpUtil.get(Globalvar.baseUrl + "/api/terms")
                .header("Accept", "application/json")
                .asJson();
        JsonNode responseBody2 = response2.getBody();
        JSONArray jsonArray2 = responseBody2.getArray();
        ObservableList<String> items02= FXCollections.observableArrayList();
        for (int i = 0; i < jsonArray2.length(); i++) {
            JSONObject jsonObject2 = jsonArray2.getJSONObject(i);
            String termname= jsonObject2.getString("name");
            Integer termId= jsonObject2.getInt("termId");//存储termId
            termName.getItems().add(termname);
            map2.put(termId, termname);
        }

        ObservableList<String> items2 = FXCollections.observableArrayList("学科基础课","专业基础课","通识核心课",
                "专业限选课","通识选修课");
        type.setItems(items2);
        ObservableList<String> items3 = FXCollections.observableArrayList("考试","考核");
        assessment.setItems(items3);
        ObservableList<String> items4 = FXCollections.observableArrayList("单周","双周","所有周");
        typeComboBox.setItems(items4);

        // ... 为其他StackPane添加点击监听器 ...
        addClickListener(stackPane1);addClickListener(stackPane2);addClickListener(stackPane3);addClickListener(stackPane4);
        addClickListener(stackPane5);addClickListener(stackPane6);addClickListener(stackPane7);addClickListener(stackPane8);
        addClickListener(stackPane9);addClickListener(stackPane10);addClickListener(stackPane11);addClickListener(stackPane12);
        addClickListener(stackPane13);addClickListener(stackPane14);addClickListener(stackPane15);addClickListener(stackPane16);
        addClickListener(stackPane17);addClickListener(stackPane18);addClickListener(stackPane19);addClickListener(stackPane20);
        addClickListener(stackPane21);addClickListener(stackPane22);addClickListener(stackPane23);addClickListener(stackPane24);
        addClickListener(stackPane25);addClickListener(stackPane26);addClickListener(stackPane27);addClickListener(stackPane28);
        addClickListener(stackPane29);addClickListener(stackPane30);addClickListener(stackPane31);addClickListener(stackPane32);
        addClickListener(stackPane33);addClickListener(stackPane34);addClickListener(stackPane35);
        }

        //设置事件处理器
        private void addClickListener(StackPane stackPane) {
            stackPane.setOnMouseClicked(event -> {
                //更新状态
                toggleSelection(stackPane);
                //printAllTimes();
            });
        }
        //更新方法
        private void toggleSelection(StackPane stackPane) {
            // 切换选中状态，使用背景颜色变化示例，同时更新jsonArray
            if (stackPane.getBackground() == null ||
                    stackPane.getBackground().getFills().isEmpty() ||
                    stackPane.getBackground().getFills().get(0).getFill().equals(Color.TRANSPARENT)) {
                stackPane.setBackground(new Background(new BackgroundFill(Color.web("#F8F5D6"), null, null)));
                updateAddJSONArray(stackPane);
            } else {
                stackPane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, null)));
                updateDeleteJSONArray(stackPane);
            }
        }
        //更新JSONArray的方法
        public void updateAddJSONArray(StackPane stackPane){
            // 获取StackPane在GridPane中的行和列索引
            int lessonNumber = GridPane.getRowIndex(stackPane);
            int dayOfWeek = GridPane.getColumnIndex(stackPane);

            // 验证索引是否有效
            if (lessonNumber < 1 || lessonNumber > 5 || dayOfWeek < 1 || dayOfWeek > 7) {
                throw new IllegalArgumentException("StackPane is not positioned properly in the GridPane");
            }

            // 创建JSONArray并添加星期和课程时间
            JSONArray innerArray = new JSONArray();
            innerArray.put(dayOfWeek); // 星期几
            innerArray.put(lessonNumber); // 第几节课
            jsonArray.put(innerArray);
        }
        public void updateDeleteJSONArray(StackPane stackPane){
            // 获取StackPane在GridPane中的行和列索引
            int lessonNumber = GridPane.getRowIndex(stackPane);
            int dayOfWeek = GridPane.getColumnIndex(stackPane);

            // 验证索引是否有效
            if (lessonNumber < 1 || lessonNumber > 5 || dayOfWeek < 1 || dayOfWeek > 7) {
                throw new IllegalArgumentException("StackPane is not positioned properly in the GridPane");
            }

            for(int i=0;i<jsonArray.length();i++){
                JSONArray innerArray = jsonArray.getJSONArray(i);
                int columnIndex = innerArray.getInt(0); // 获取星期几
                int rowIndex = innerArray.getInt(1); // 获取第几节课
                if ((columnIndex == dayOfWeek) && (rowIndex == lessonNumber)) {
                    set_Delete(stackPane,innerArray);
                    jsonArray.remove(i);
                }
            }
        }
    public void set_Delete(StackPane stackPane, JSONArray innerArray) {
        if (!innerArray.isEmpty()) {
            stackPaneToTimeMap.remove(stackPane);
        }
    }

    public void collegeComboBoxClickedHandler() {
        String selectedCollege =collegeName.getValue();
        String targetValue = selectedCollege;
        int collegeId =0;
        for (Map.Entry<Integer, String> entry : map1.entrySet()) {
            if (entry.getValue().equals(targetValue)) {
                collegeId = entry.getKey();
                collegeid=collegeId;
                break; // 找到匹配值后跳出循环
            }
        }
    }
    public void termComboBoxClickedHandler() {
        String selectedTerm =termName.getValue();
        String targetValue = selectedTerm;
        int termId =0;
        for (Map.Entry<Integer, String> entry : map2.entrySet()) {
            if (entry.getValue().equals(targetValue)) {
                termId = entry.getKey();
                termid=termId;
                break; // 找到匹配值后跳出循环
            }
        }
    }

    public void submitButtonClick() {
        try {
            JSONObject timeDetails = new JSONObject();
            String type0 ="all";
            if(Objects.equals(type.getValue(), "单周")){
                type0="odd";
            }
            else if(Objects.equals(type.getValue(), "双周")){
                type0="even";
            }
            else if(Objects.equals(type.getValue(), "所有周")){
                type0="all";
            }
            timeDetails.put("from", Integer.parseInt(from.getText()));
            timeDetails.put("to", Integer.parseInt(to.getText()));
            timeDetails.put("type", type0);

            JSONArray timeArray = new JSONArray();

            for (String cell : selectedCells) {
                String[] parts = cell.split(",");
                int row = Integer.parseInt(parts[0]) ;
                int col = Integer.parseInt(parts[1]) ;
                JSONArray coords = new JSONArray();
                coords.put(row);
                coords.put(col);
                timeArray.put(coords);
            }
            //根据选择的天数和节数这组数据的组数动态创建time数组
            timeDetails.put("time", timeArray);

            String assessment1 ="GRADE";
            if(Objects.equals(type.getValue(), "考试")){
                assessment1="GRADE";
            }
            else if(Objects.equals(type.getValue(), "考核")){
                assessment1="SCORE";
            }

            JSONObject requestBody = new JSONObject();
            requestBody.put("name", name.getText());
            requestBody.put("termId", termid);
            requestBody.put("collegeId", collegeid);
            requestBody.put("teacherId", Long.parseLong(teacherId.getText()));
            requestBody.put("type", type.getValue());
            requestBody.put("credit", new BigDecimal(credit.getText()));
            requestBody.put("description", description.getText());
            requestBody.put("time", timeDetails);
            requestBody.put("location", Location.getText());
            requestBody.put("capacity", Integer.parseInt(capacity.getText()));
            requestBody.put("assessment", assessment1);

            HttpResponse<JsonNode> response = HttpUtil.post(Globalvar.baseUrl+"/api/courses")
                    .header("Content-Type", "application/json")
                    .body(requestBody.toString())
                    .asJson();
            success.setVisible(false);
            if(response.getStatus() == 201) {
                success.setVisible(true);
                clearSelection();
                // 注册成功给用户提示，维持3秒
                Timer successTimer = new Timer();
                successTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        success.setVisible(false);
                    }
                }, 3000); // 3000 milliseconds = 3 seconds
            }
            System.out.println("Response status: " +response.getStatus());
            System.out.println("Response body: " + response.getBody().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void clearSelection() {
        for (StackPane stackPane : new StackPane[]{stackPane1, stackPane2, stackPane3, stackPane4, stackPane5,
                stackPane6, stackPane7, stackPane8, stackPane9, stackPane10, stackPane11, stackPane12, stackPane13,
                stackPane14, stackPane15, stackPane16, stackPane17, stackPane18, stackPane19, stackPane20, stackPane21,
                stackPane22, stackPane23, stackPane24, stackPane25, stackPane26, stackPane27, stackPane28, stackPane29,
                stackPane30, stackPane31, stackPane32, stackPane33, stackPane34, stackPane35}) {
            stackPane.setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, null, null)));
        }
        // 清空所有文本字段
        name.clear();
        teacherId.clear();
        credit.clear();
        Location.clear();
        capacity.clear();
        from.clear();
        to.clear();
        description.clear();

        // 清空 Combobox
        collegeName.getSelectionModel().clearSelection();
        termName.getSelectionModel().clearSelection();
        type.getSelectionModel().clearSelection();
        assessment.getSelectionModel().clearSelection();
        typeComboBox.getSelectionModel().clearSelection();

        // 清空其他变量或集合
        jsonArray = new JSONArray();
        stackPaneToTimeMap.clear();
        selectedCells.clear();
    }
}